<!-- components/DirectorySwitcher.vue -->
<template>
    <div class="grid-cols-2 grid justify-items-center text-gray-900 uppercase font-bold mb-2">
        <span class="col-span-1" @click="toggleShowToc(true)"
            :class="[showToc ? 'text-sky-600 dark:text-sky-500' : '']">
            文章目录
        </span>
        <span class="col-span-1" @click="toggleShowToc(false)"
            :class="[!showToc ? 'text-sky-600 dark:text-sky-500' : '']">
            知识库目录
        </span>
    </div>
    <slot v-if="showToc"></slot>
    <div v-else>
        <el-collapse accordion v-model="activeCollapseId">
            <el-collapse-item v-for="(catalog, index) in catalogs" :key="index" :title="catalog.title"
                :name="catalog.id" :active="catalog.children.some(child => child.articleId === route.query.articleId)">
                <div v-for="(childCatalog, index2) in catalog.children" :key="index2"
                    :class="[childCatalog.articleId == route.query.articleId ? 'bg-sky-50 text-sky-600 dark:bg-sky-950 dark:text-sky-500' : 'hover:bg-gray-100 dark:hover:bg-gray-800']"
                    @click="goWikiArticleDetailPage(childCatalog.articleId)">
                    {{ childCatalog.title }}
                </div>
            </el-collapse-item>
        </el-collapse>
    </div>
</template>

<script setup>
import { watch, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getWikiCatalogs } from '@/api/frontend/wiki'

const route = useRoute()
const router = useRouter()

const props = defineProps({
    isShowToc: {
        type: Boolean,
        required: false,
    },
})


let showToc = ref(true)

// 打开的面板组
let activeCollapseId = ref("")
const catalogs = ref()

watch(props, (New, Old) => {
    console.log("New.isShowToc", New.isShowToc)
    showToc.value = New.isShowToc
})

const toggleShowToc = (value) => {
    showToc.value = value
}

// 获取当前知识库的目录数据
getWikiCatalogs(route.params.wikiId).then(res => {
    if (res.success) {
        catalogs.value = res.data
        // 获取数据成功后，初始化 组件
        const catalog = catalogs.value.find(item =>
            item.children.find(child => child.articleId == route.query.articleId));
        activeCollapseId.value = catalog.id;
    }
})

// 跳转文章详情页
const goWikiArticleDetailPage = (articleId) => {
    router.push({ path: '/wiki/' + route.params.wikiId, query: { articleId } })
}
</script>